const ethereumWallet = require('ethereumjs-wallet');
const Web3 = require('web3');
const EthereumTx = require('ethereumjs-tx')
const axios = require('axios')
// const testnet = 'https://mainnet.infura.io/v3/73f861f921124507acf2a196740cf0b9';
const testnet = 'https://ropsten.infura.io/v3/73f861f921124507acf2a196740cf0b9';
const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
const log = require('ololog').configure({ time: true })

const getCurrentGasPrices = async () => {
  let response = await axios.get('https://ethgasstation.info/json/ethgasAPI.json')
  let prices = {
    low: response.data.safeLow / 10,
    medium: response.data.average / 10,
    high: response.data.fast / 10
  }
  console.log("\r\n")
  log (`Current ETH Gas Prices (in GWEI):`.cyan)
  console.log("\r\n")
  log(`Low: ${prices.low} (transaction completes in < 30 minutes)`.green)
  log(`Standard: ${prices.medium} (transaction completes in < 5 minutes)`.yellow)
  log(`Fast: ${prices.high} (transaction completes in < 2 minutes)`.red)
  console.log("\r\n")
 
  return prices
}
/* var version = web3.version.api;
            
axios.get('http://api.etherscan.io/api?module=contract&action=getabi&address=0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359')
.then(({data}) => {
  var contractABI = "";
  contractABI = JSON.parse(data.result);
  if (contractABI != ''){
      var MyContract = web3.eth.Contract(contractABI);
      var myContractInstance = MyContract.at("0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359");
      var result = myContractInstance.memberId("0xfe8ad7dd2f564a877cc23feea6c0a9cc2e783715");
      console.log("result1 : " + result);            
      var result = myContractInstance.members(1);
      console.log("result2 : " + result);
  } else {
      console.log("Error" );
  }            
}) */
module.exports = function (app) {
  app.use('/api/eth/newWallet', {
    find: () => {
      const addressObj = ethereumWallet.generate()
      const address = addressObj.getChecksumAddressString()
      const privateKey = addressObj.getPrivateKeyString()
      return Promise.resolve({
        address,
        privateKey
      })
    }
  })
  app.use('/api/eth/getBalance', {
    find: async ({query:{address}}) => {
      let myBalanceWei = await web3.eth.getBalance(address)
      let myBalance = web3.utils.fromWei(myBalanceWei, 'ether')
  
      log(`Your wallet balance is currently ${myBalance} ETH`.green)
      return Promise.resolve({
        balance: myBalance
      })
    }
  })
  app.use('/api/eth/transfer', {
    find: async ({query:{fromAddress, toAddress, wif ,amount}}) => {
      try {
        debugger
        let nonce = await web3.eth.getTransactionCount(fromAddress)
        let gasPrices = await getCurrentGasPrices()
        let details = {
          "to": toAddress,
          "value": web3.utils.toHex( web3.utils.toWei(amount, 'ether') ),
          "gas": 21000,
          "gasPrice": gasPrices.low * 1000000000, // converts the gwei price to wei
          "nonce": nonce,
          "chainId": 1 // EIP 155 chainId - mainnet: 1, rinkeby: 4
        }
        const transaction = new EthereumTx(details)
        const key = new Buffer(wif, 'hex') 
        transaction.sign(key)
        const serializedTransaction = transaction.serialize()
        web3.eth.sendSignedTransaction('0x' + serializedTransaction.toString('hex'), () => {
          debugger
        })
        return {
          success: true
        }
      } catch (e) {
        console.log(e)
        return {
          success: false,
          msg: '参数不正确'
        }
      }
      
    }
  })
} 